﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crawler.Model;
using Husb.Framework.DataAccess;
using System.Data;
using System.IO;
using System.Data.Common;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Practices.EnterpriseLibrary.Data;


namespace Crawler.DataAccess
{
    public partial class WebPageDao : DataAccessBase<WebPageInfo>
    {
        public const string GetCountByUrlStatement = "Crawler.WebPages_SelectWebPageByUrl";
        public const string GetContentStatement = "Crawler.WebPages_SelectWebPageContent";


        public const string htmlHeader = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"">
 <head><title> new document </title><meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8""/> </head><body>";
        public const string htmlFooter = "</body></html>";




       

        public int GetCountByUrl(String url)
        {
            List<DatabaseParameter> parameters = new List<DatabaseParameter>();
            parameters.Add(new DatabaseParameter("Url", DbType.String, url));

            object cnt = this.GetValue(GetCountByUrlStatement, parameters, null, false, null, this.CommandType);
            if (cnt == null)
                return 0;
            return (int)cnt;
        }

        //public string GetArticleContent(int id)
        //{
        //    string data = null;
        //    const int articleColumn = 0;

        //    Database db = DatabaseFactory.CreateDatabase();
        //    DbCommand cmd = db.GetSqlStringCommand(GetArticleById);

        //    db.AddInParameter(cmd, "ID", DbType.Int32, id);

        //    using (IDataReader dr = db.ExecuteReader(cmd))
        //    {
        //        if (dr.Read())
        //        {
        //            using (MemoryStream ms = new MemoryStream())
        //            {
        //                const int bufferSize = 100;
        //                byte[] buffer = new byte[bufferSize];
        //                int byteCountRead;
        //                long currentIndex = 0;
        //                byteCountRead = (int)dr.GetBytes(articleColumn, currentIndex, buffer, 0, bufferSize);
        //                while (byteCountRead != 0)
        //                {
        //                    ms.Write(buffer, 0, byteCountRead);
        //                    currentIndex += byteCountRead;
        //                    byteCountRead = (int)dr.GetBytes(articleColumn, currentIndex, buffer, 0, bufferSize);
        //                }
        //                ms.Position = 0;
        //                GZipStream compressionStream = new GZipStream(ms, CompressionMode.Decompress);
        //                StreamReader reader = new StreamReader(compressionStream);
        //                data = reader.ReadToEnd();
        //                reader.Close();
        //                //return data;
        //            }
        //        }
        //    }

        //    return data;
        //}

        public bool GetArticleContent(Guid id, string path)
        {
            bool hasArticle = false;
            //string fileName = null;
            const int articleColumn = 0;

            List<DatabaseParameter> parameters = new List<DatabaseParameter>();
            parameters.Add(new DatabaseParameter("Id", DbType.Guid, id));

            byte[] buffer = this.GetBytes(GetContentStatement, articleColumn, parameters);
            using (MemoryStream ms = new MemoryStream(buffer))
            using (ZipInputStream s = new ZipInputStream(ms))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);
                    if (theEntry.Comment != null && theEntry.Comment.Length > 0)
                    {
                        fileName = Path.GetFileName(theEntry.Comment);
                    }

                    // create directory
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(path + directoryName);
                    }

                    if (fileName != String.Empty)
                    {
                        using (FileStream fs = new FileStream(path + fileName, FileMode.OpenOrCreate, FileAccess.Write))//theEntry.Name
                        {
                            //int size = 4096;
                            //byte[] data = new byte[size];
                            //while (true)
                            //{
                            //    size = s.Read(data, 0, data.Length);
                            //    if (size > 0)
                            //    {
                            //        fs.Write(data, 0, size);
                            //    }
                            //    else
                            //    {
                            //        break;
                            //    }
                            //}

                            if (theEntry.Name == "ArticleContent.htm")
                            {
                                byte[] bsH = System.Text.Encoding.UTF8.GetBytes(htmlHeader);
                                fs.Write(bsH, 0, bsH.Length);
                            }



                            int readCount;
                            byte[] data = new byte[1024];
                            while ((readCount = s.Read(data, 0, data.Length)) != 0)
                            {
                                fs.Write(data, 0, readCount);
                            }
                            if (theEntry.Name == "ArticleContent.htm")
                            {
                                byte[] bsF = System.Text.Encoding.UTF8.GetBytes(htmlFooter);
                                fs.Write(bsF, 0, bsF.Length);
                            }
                        }
                    }
                }
                hasArticle = true;
            }


            return hasArticle;
        }

        //public bool GetArticleContent(Guid id, string path)
        //{
        //    bool hasArticle = false;
        //    //string fileName = null;
        //    const int articleColumn = 0;

        //    Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase();
        //    DbCommand cmd = db.GetStoredProcCommand(GetContentStatement);

        //    db.AddInParameter(cmd, "Id", DbType.Guid, id);

        //    using (IDataReader dr = db.ExecuteReader(cmd))
        //    {
        //        if (dr.Read() && !dr.IsDBNull(articleColumn))
        //        {
        //            #region DBNull.Value
        //            using (MemoryStream ms = new MemoryStream())
        //            {
        //                const int bufferSize = 4096;
        //                byte[] buffer = new byte[bufferSize];
        //                int byteCountRead;
        //                long currentIndex = 0;
        //                //byteCountRead = (int)dr.GetBytes(articleColumn, currentIndex, buffer, 0, bufferSize);
        //                while ((byteCountRead = (int)dr.GetBytes(articleColumn, currentIndex, buffer, 0, bufferSize)) != 0)
        //                {
        //                    ms.Write(buffer, 0, byteCountRead);
        //                    currentIndex += byteCountRead;
        //                    //byteCountRead = (int)dr.GetBytes(articleColumn, currentIndex, buffer, 0, bufferSize);
        //                }
        //                if (ms.Length > 0 && ms.Position != 0)
        //                {
        //                    ms.Position = 0;
        //                }

        //                #region ZipInputStream
        //                using (ZipInputStream s = new ZipInputStream(ms))
        //                {
        //                    ZipEntry theEntry;
        //                    while ((theEntry = s.GetNextEntry()) != null)
        //                    {
        //                        //Console.WriteLine(theEntry.Name);
        //                        string directoryName = Path.GetDirectoryName(theEntry.Name);
        //                        string fileName = Path.GetFileName(theEntry.Name);

        //                        // create directory
        //                        if (directoryName.Length > 0)
        //                        {
        //                            Directory.CreateDirectory(path + directoryName);
        //                        }

        //                        if (fileName != String.Empty)
        //                        {
        //                            using (FileStream fs = new FileStream(path + theEntry.Name, FileMode.OpenOrCreate, FileAccess.Write))//theEntry.Name
        //                            {
        //                                int size = 4096;
        //                                byte[] data = new byte[4096];
        //                                while (true)
        //                                {
        //                                    size = s.Read(data, 0, data.Length);
        //                                    if (size > 0)
        //                                    {
        //                                        fs.Write(data, 0, size);
        //                                    }
        //                                    else
        //                                    {
        //                                        break;
        //                                    }
        //                                }

        //                                //int readCount;
        //                                //byte[] data = new byte[1024];
        //                                //while ((readCount = ms.Read(data, 0, data.Length)) != 0)
        //                                //{
        //                                //    fs.Write(data, 0, readCount);
        //                                //}
        //                            }
        //                        }
        //                    }
        //                    hasArticle = true;
        //                }
        //                #endregion ZipInputStream
        //            }
        //            #endregion
                       
        //        }
        //    }

        //    return hasArticle;
        //}


        
    }
}
